from bson import ObjectId
import os
import random
import datetime
from flask import current_app
from werkzeug.utils import secure_filename

from lina.mongodb import db
from lina.service.BaseService import BaseService


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in set(['png', 'jpg', 'jpeg', 'JPG', 'PNG', 'gif', 'GIF'])


def create_uuid():  # 生成唯一的图片的名称字符串，防止图片显示时的重名问题
    nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S")  # 生成当前时间
    randomNum = random.randint(0, 100)  # 生成的随机整数n，其中0<=n<=100
    if randomNum <= 10:
        randomNum = str(0) + str(randomNum)
    uniqueNum = str(nowTime) + str(randomNum)
    return uniqueNum


class AttachmentService(BaseService):

    def __init__(self):
        self.table_name = 'attachment'
        super().__init__()

    def add_attachment(self, case_id, f):
        # 添加附件图片
        img_dir = current_app.config['IMG_FOLDER']
        if not os.path.exists(img_dir):
            os.makedirs(img_dir)

        if f and allowed_file(f.filename):
            fname = secure_filename(f.filename)
            ext = fname.rsplit('.', 1)[1]
            new_filename = create_uuid() + '.' + ext

            f.save(os.path.join(img_dir, new_filename))
           
            caseId = ObjectId(case_id)
            table = db()[self.table_name]
            result = table.insert_one({
                "case_id": caseId,
                "file_name": new_filename
            })

            return table.find_one({"_id": ObjectId(result.inserted_id)})

        return None

    def get_pic_by_case_id(self, case_id):
        # 查询案件的所有附件图片
        caseId = ObjectId(case_id)
        pic_list = []
        table = db()[self.table_name]
        for pic in table.find({"case_id": caseId}):
            pic_list.append(pic)
        return pic_list

    def remove(self, file_id):

        table = db()[self.table_name]
        objId = ObjectId(file_id)
        table.remove({"_id": objId})
